

function test1(delay, callback) {
	delay = delay ||  2000
	setTimeout( () => {
		console.log('setTimeout 执行完毕')
	}, delay)

	// 怎样保证setTimeout执行完毕之后 执行后面的 callback回到
	callback && callback()
}


// test1(2000, function() {
// 	console.log('callback done')
// })
// 



class Animation {
	// 动画是否执行完成的标识
	animateDone = false ;
	count = 1;

	constructor(id) {
		this.id = id ;
	}


	show(callback) {
		if(this.animateDone) return ;
		this.animateDone = false 
		setTimeout(() => {
			console.log('show(callback): show ' + --this.count)
			this.animateDone = true 
			callback && callback();
		}, 1000) 
	}
	hide(callback) {
		if(this.animateDone) return ;

		this.animateDone = false 
		setTimeout(() => {
			console.log('hide ' + ++this.count)
			this.animateDone = true 
			callback && callback();
		}, 1000) 
	}

	static createBatch(num) {
		var list = []
		for (var i = 1; i <= num; i++) {
			list.push(new this(i))
		}
		return list
	}



	static showAllV1(list, callback) {
		
		// 需要保证forEach全部回调后才能执行 后续的callback
		// 全部都完成后 才能执行callback 
		list.forEach((item, i) => {
			item.show(()=> {
				console.log('showAll ' + i)
			})
		})
		console.log('showAll ....')
		callback && callback()
	}


	static num = 0

	// 回调加上计数器的方案
	static showAllV2(list, callback) {
		
		// 需要保证forEach全部回调后才能执行 后续的callback
		// 全部都完成后 才能执行callback 
		list.forEach((item, i) => {
			item.show(()=> {
				console.log('showAll ' + i)
				// 完成一个 +1
				// 说明全部完成了
				if(++this.num == list.length) {
					console.log(`showAll  done ....... ${this.num}`)
					this.num = 0
					callback && callback()
				}
			})
		})
	}

	// promise 方案
	static showAllV3(list, callback) {
		return new Promise((resolve, reject) => {
			// 需要保证forEach全部回调后才能执行 后续的callback
			// 全部都完成后 才能执行callback 
			list.forEach((item, i) => {
				item.show(()=> {
					console.log('showAll ' + i)
					// 完成一个 +1
					// 说明全部完成了
					if(++this.num == list.length) {
						resolve('hahh')
					}
				})
			})
		}).then(value => {
			console.log(`then showAll  done ${value}....... ${this.num}`)
			this.num = 0
			callback && callback()
		})
	}

	// 采用Promise.all
	static showAll(list, callback) {
		Promise.all(list.map((item, i) => {
			return new Promise((resolve, reject)=> {
				item.show(() => {
					console.log('showAll ' + i)
					resolve('promise showAll ' + i)
				})
			})
		})).then(value => {
			console.log('-----------------------\n')
			console.log(value)
			console.log(`promise then showAll  done ....... ${this.num}`)
			callback && callback()
		})
	}
}


var list = Animation.createBatch(3);
var a1 = new Animation()

Animation.showAll(list, function( ) {
	console.log('showAll 动画执行完成')
})

/*
console.log(a1)
console.time('show')
a1.show(function() {
	console.log('sdfsdfsdf')
	console.timeEnd('show')
});

console.log(list)
*/

